package com.jdk.learn.juc2.thread;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 类功能描述:
 *
 * @author bgt
 * @version V1.0
 * @since 2019-01-30 16:29
 */
public class ThreadWaitAndNotify {

    public static void main(String[] args) throws InterruptedException {
        Queue<String> queue = new ArrayBlockingQueue<>(5);

        Thread Producer = new Thread(() -> {
            Producer producer = new Producer();
            for (int i = 0; i < 1000; i++) {
                try {
                    producer.set(queue);
                    if (i==999) System.out.println("p==end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread Consumer = new Thread(() -> {
            Consumer consumer = new Consumer();
            for (int i = 0; i < 1000; i++) {
                try {
                    consumer.get(queue);
                    if (i==999) System.out.println("c==end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Producer.start();
        Consumer.start();
        Producer.join();
        Consumer.join();
    }

}

class Producer {
    public void set(Queue<String> queue) throws InterruptedException {
        synchronized (queue) {
            while (queue.size() ==5) {
              queue.wait();
            }
            String str="apple" + new Random().nextFloat();
            queue.add(str);
            System.out.println("add:"+str);
            queue.notifyAll();
        }
    }
}

class Consumer {

    public void get(Queue<String> queue) throws InterruptedException {
        synchronized (queue) {
            while (queue.size() == 0) {
               queue.wait();
            }
            String poll = queue.poll();
            System.out.println("use:"+poll);

            queue.notifyAll();
        }
    }
}